<template>
  <div>
    <div class="flex gap2">
      <ElSelect v-model="columnName" class="w100px">
        <ElOption v-for="(column, columnName) in columnOptions" :label="column.label" :value="columnName" :key="columnName" />
      </ElSelect>
      <ElButton @click="add">+</ElButton>
    </div>
    
    <div v-for="(, columnName) in data" :key="columnName" class="flex gap2">
      <div class="w200px">{{ columns[columnName].label }}</div>
      <ElInput v-model="data[columnName]" size="small" />
      <ElButton type="danger" size="small" @click="remove(columnName)">删除</ElButton>
    </div>
  </div>
</template>
<script setup lang="ts">
  import feedback from '@/utils/feedback';
  import { ColumnConfiguration } from '@/views/dev-types';
  import { getSeed } from '@/views/seed-dev';
  import { RelationType } from '@/views/types';
  import { ElSelect, ElOption, ElInput, ElButton } from 'element-plus';
  import { computed, ref, watch } from 'vue';

  const props = defineProps<{
    modelValue?: Record<string, any>,
    selfSeedName: string,
    targetSeedName?: string,
    throughSeedName?: string,
    type: RelationType
  }>()
  const emits = defineEmits(['update:modelValue'])

  const columnName = ref<string>()
  function add() {
    if(columnName) {
      data.value[columnName.value] = void 0
      columnName.value = void 0
    } else {
      feedback.msgError('请选择要添加的列')
    }
  }

  function remove(columnName: string) {
    delete data.value[columnName]
  }

  const columnOptions = computed(() => {
    const type = props.type
    const seedName = type === 'belongsTo' ? props.selfSeedName : (type === 'habtm' ? props.throughSeedName : props.targetSeedName)
    if(!seedName) return {}

    const columns = getSeed(seedName).columns
    const ret: Record<string, ColumnConfiguration> = {}
    for(const columnName in columns) {
      if(!Object.keys(data.value).includes(columnName)) ret[columnName] = columns[columnName]
    }

    return ret
  })

  const columns = computed(() => {
    const type = props.type
    const seedName = type === 'belongsTo' ? props.selfSeedName : (type === 'habtm' ? props.throughSeedName : props.targetSeedName)
    if(!seedName) return {}

    return getSeed(seedName).columns
  })

  const data = ref<Record<string, any>>(props.modelValue || {})

  watch(() => props.modelValue, (val) => data.value = val || {}, {deep: true})
  watch(data, (val) => emits('update:modelValue', val), {deep: true})
</script>